package org.loneranger.p6_initialization;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class InitBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return null;
    }


    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (beanName.equals("initService")) {
            System.out.println("实例化后");
        }
        return true;
    }

    /**
     * 如果有多个beanPostProcessor，如果该方法返回了null，则其他的beanPostProcessor无法执行
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("initService")) {
            System.out.println("初始化前");
        }
        return bean;
    }

    /**
     * Spring实现AOP就是在初始化后
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("initService")) {
            System.out.println("初始化后");
        }
        return bean;
    }
}
